﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace WD.Web.MVC.Controllers.Filters
{
    /// <summary>   
    /// 基本验证Attribtue，用以WebApi请求的权限处理   
    /// </summary>   
    public class BasicAuthenticationAttribute : ActionFilterAttribute
    {
        /// <summary>   
        /// 检查用户是否有该WebApi请求执行的权限   
        /// </summary>   
        /// <param name="actionContext"></param>   
        public override void OnActionExecuting(HttpActionContext actionContext)
        {

            if (actionContext.Request.Headers.Contains("access_token"))
            {
                var accessToken = actionContext.Request.Headers.GetValues("access_token");
                if (accessToken!=null)
                {
                   var strToken =  accessToken.FirstOrDefault();
                    //验证token 是否有效
                   if (ValidateToken(strToken))
                   {
                       //验证通过
                       base.OnActionExecuting(actionContext);
                       return;
                   }
                }
            }
            //失败
            actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
            ApiResult ajax = new ApiResult();
            actionContext.Response.Content = new StringContent(ajax.Err("无效在token").ToString(),
                                                  Encoding.UTF8, "text/plain");
        }

        /// <summary>
        /// 验证是否登录授权
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public bool ValidateToken(string token)
        {
            if (!string.IsNullOrEmpty(token))
            {
                //调用接口验证token是否有效
                //var model = cache.Get<LoginMember>(token);
                //Logger.Error("2:请求中的。。。:model:" + model == null ? "不存在" : model.UserName);

                return token == "111" ? true : false;
            }
            return false;
        }
    }
}